<template>
  <a-modal
    :title="modalTitle"
    width="70%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" style="max-height: 550px;overflow-y: auto;overflow-x: hidden;">
        <a-form-item label="业务ID" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false">
          <a-input v-if="modalOpera==1" v-decorator="['id', {rules: [{required: true}]}]" />
        </a-form-item>
        <p>
          基础信息
          <a-icon type="right" />
        </p>
        <a-row :gutter="12">
          <a-col :xl="{span: 8}" :lg="{span: 8}" :md="{span: 12}">
            <a-form-item label="模型名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['name', {rules: [{required: true, min: 2, message: '请输入至少二个字符的规则！'}]}]" />
            </a-form-item>
          </a-col>
          <a-col :xl="{span: 16}" :lg="{span: 8}" :md="{span: 12}">
            <a-form-item label="模型选项" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-checkbox
                :value="moption.value"
                :key="moption.value"
                :checked="moptions.indexOf(moption.value) >=0"
                v-for="moption in modelOptions"
                @change="onChangeMoption">{{ moption.label }}</a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="12">
          <a-col :xl="{span: 8}" :lg="{span: 8}" :md="{span: 24}">
            <a-form-item label="内容模板" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <!-- <a-input-search
                placeholder="点击放大镜选择内容模板"
                v-decorator="['templatePath', {rules: [{required: false, message: '请输入至少三个字符的规则！'}]}]"
                @search="onSearchTemp"
                readonly="readonly" /> -->
              <a-tree-select
                v-decorator="['md5Key', {rules: [{required: true, message: '请选择模板'}]}]"
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                @change="changeTemplate"
                placeholder="请先安装模板后在选择模板"
                tree-default-expand-all
              >
              </a-tree-select>
            </a-form-item>
          </a-col>

          <a-col :xl="{span: 16}" :lg="{span: 8}" :md="{span: 12}">
            <a-form-item label="" :labelCol="{xs: {span: 24}}" :wrapperCol="wrapperCol">
              <span @click="loadTemplate"><a-icon type="reload" v-if="!reloading"/></span>
              <span><a-icon type="loading" v-if="reloading"/></span>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="模板地址" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false">
          <a-input v-decorator="['templatePath', {rules: [{required: true, message: '请输入至少二个字符的规则！'}]}]" />
        </a-form-item>

        <a-form-item label="模型ID" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false">
          <a-input v-decorator="['templateId', {rules: [{required: true, message: '请输入至少二个字符的规则！'}]}]" />
        </a-form-item>

        <a-form-item label="模型模板ID" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="false">
          <a-input v-decorator="['modelTemplateId', {rules: [{required: false, message: '请输入至少二个字符的规则！'}]}]" />
        </a-form-item>

        <a-divider dashed />

        <p>
          内容系统字段
          <a-icon type="right" />
        </p>

        <a-row :gutter="6" v-for="(field,index) in fields" :key="index">
          <a-col :xl="{span: 5}" :lg="{span: 8}" :md="{span: 24}">
            <a-form-item :label="field.fieldName" :labelCol="labelCol" :wrapperCol="{xs: {span: 24},sm:{ span: 4}}">
              <a-checkbox :value="field.fieldName" :checked="field.check" v-if="field.fieldCode!=='title'" @change="checkField($event,field)"></a-checkbox>
            </a-form-item>
          </a-col>

          <a-col :xl="{span: 6}" :lg="{span: 6}" :md="{span: 24}">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <p>{{ field.fieldName }}( {{ field.fieldCode }} )</p>
            </a-form-item>
          </a-col>

          <a-col :xl="{span: 5}" :lg="{span: 8}" :md="{span: 24}" v-if="field.check">
            <a-form-item label="必填" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-switch v-model="field.isRequired" />
            </a-form-item>
          </a-col>

          <a-col :xl="{span: 5}" :lg="{span: 8}" :md="{span: 24}" v-if="field.check">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-model="field.fieldAliase" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-divider dashed />
        <extend-model ref="extendModel" />
      </a-form>
      <!-- <search-temp ref="searchTemp" @ok="confirm"></search-temp> -->
    </a-spin>
  </a-modal>
</template>

<script>
  import {
    save,
    getById,
    update,
    loadModel,
    loadTemplate
  } from '@/api/site/model'
  // import searchTemp from './searchTemp'
  import pick from 'lodash.pick'
  import ExtendModel from '@/components/ExtendModel/ExtendModel.vue'
  export default {
    components: {
      // searchTemp,
      ExtendModel
    },
    data () {
      return {
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 7
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 13
          }
        },
        modalTitle: '',
        modalOpera: 0, // 0：新增 1：编辑
        visible: false,
        confirmLoading: false,
        reloading: false,
        modelOptions: [{
            label: '超链接',
            value: 'isUrl'
          },
          {
            label: '含附件',
            value: 'hasFiles'
          },
          {
            label: '引用公众号文章',
            value: 'supportWehcat'
          },
          {
            label: '引用头条文章',
            value: 'supportTops'
          }
        ],
        moptions: [],
        fields: [],
        treeData: [],
        templateId: null,
        form: this.$form.createForm(this)
      }
    },
    created () {
      this.loadModelField()
      this.loadTemplate()
    },
    mounted () {
      // this.inputType = inputTypes;
    },
    methods: {
      add () {
        this.modal('新建模型', 0)
      },
      edit (record) {
        const that = this
        this.modal('编辑模型', 1)
        setTimeout(function () {
          that.getDetail(record)
        }, 100)
      },
      modal (title, opera) {
        this.modalTitle = title
        this.modalOpera = opera
        this.visible = true
        this.form.resetFields()
      },
      loadModelField () {
        loadModel().then(response => {
          this.fields = response.res
        })
      },
      loadTemplate () {
        this.reloading = true
        loadTemplate().then(response => {
          if (response.code === 0) {
            this.treeData = response.res.templateFiles
            this.templateId = response.res.templateId
            this.reloading = false
          }
        })
      },
      // confirm (path) {
      //  this.form.setFieldsValue({
      //    templatePath: path
      //  })
      // },
      changeTemplate (value, label, e) {
        this.form.setFieldsValue({
          templatePath: e.triggerNode.dataRef.relativePath
        })
        this.form.setFieldsValue({
          templateId: this.templateId
        })
      },
      getDetail (record) {
        getById({
          pk: record.id
        }).then(response => {
          const result = response.res
          this.form.setFieldsValue(pick(result, 'id', 'name', 'templateId', 'templatePath', 'modelTemplateId'))
          if (this.treeData.length > 0) {
             this.form.setFieldsValue({ md5Key: result.md5Key })
          }
          if (result.extendFieldList) {
            this.$refs.extendModel.setDataSource(JSON.parse(result.extendFieldList))
          }
          if (result.defaultFieldList) {
            this.fields = JSON.parse(result.defaultFieldList)
          }
          this.setModelOptions(result)
        })
      },
      handleSubmit () {
        const {
          form: {
            validateFields
          }
        } = this
        validateFields((errors, values) => {
          if (!errors) {
            this.confirmLoading = true
            const param = this.bulidData(values)
            console.log(param)
            this.confirmLoading = true
            if (this.modalOpera === 0) {
              save(param).then(response => {
                if (response.code === 0) {
                  this.$message.info(response.msg)
                  this.$emit('ok')
                  this.handleCancel()
                } else {
                  this.$message.error(response.msg)
                }
              })
            } else if (this.modalOpera === 1) {
              update(param).then(response => {
                if (response.code === 0) {
                  this.$message.info(response.msg)
                  this.$emit('ok')
                  this.handleCancel()
                } else {
                  this.$message.error(response.msg)
                }
              })
            }
          }
          this.confirmLoading = false
        })
      },
      bulidData (values) {
        const param = {
          id: values.id,
          name: values.name,
          templatePath: values.templatePath,
          templateId: values.templateId,
          modelTemplateId: values.modelTemplateId,
          isUrl: this.moptions.indexOf('isUrl') >= 0,
          hasFiles: this.moptions.indexOf('hasFiles') >= 0,
          hasImages: this.moptions.indexOf('hasImages') >= 0,
          supportWehcat: this.moptions.indexOf('supportWehcat') >= 0,
          supportTops: this.moptions.indexOf('supportTops') >= 0,
          defaultFieldList: JSON.stringify(this.fields),
          extendFieldList: JSON.stringify(this.$refs.extendModel.getDataSource())
        }
        return param
      },
      handleCancel () {
        this.moptions = []
        this.initFields()
        this.visible = false
        this.confirmLoading = false
      },
      onChangeMoption (moption) {
        const value = moption.target.value
        if (moption.target.checked) {
          this.moptions.push(value)
        } else {
          const index = this.moptions.indexOf(value)
          this.moptions.splice(index, 1)
        }
      },
      checkField (e, field) {
          field.check = e.target.checked
      },
      setModelOptions (obj) {
        const that = this
        this.modelOptions.forEach(function (item, index) {
          if (obj && obj[item.value]) {
            that.moptions.push(item.value)
          }
        })
      },
      onSearchTemp () {
        this.$refs.searchTemp.selectTemp()
      },
      setDataSource (data) {
        // this.$refs.inputType.setDataSource(data)
      },
      initFields () {
        this.loadModelField()
        this.$refs.extendModel.clearDataSource()
      }
    }
  }
</script>

<style type="text/css">
  ::-webkit-scrollbar-track-piece {
  background-color:#ffffff!important;
  }
  ::-webkit-scrollbar {
  width:9px;
  height:9px;
  }
  ::-webkit-scrollbar-thumb {
  background-color:#ffffff!important;
  background-clip:padding-box;
  min-height:28px;
  }
  ::-webkit-scrollbar-thumb:hover {
  background-color:#ffffff!important;
  }

  .ant-col-sm-13 {
     width: 70.166667%;
  }
</style>
